/*
 * GoogleMaps.java
 *
 * Created on 23 de Abril de 2007, 0:42
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package services.MapServices;

import Utils.HTTP;
import Utils.REST;
import java.io.InputStream;
import java.util.Scanner;

/**
 *
 * @author JAKE
 */
public class GoogleMaps extends MapService{
    
    private String api_key;
    private String output;
    
    /** Creates a new instance of GoogleMaps */
    public GoogleMaps() {
        api_key="ABQIAAAAxWVNSGc1okG9T7MpgQWr6xR5owBxYXzFAueWBGA5V7et2SXgsxQzBNz83O2tl_nbuv2-G-m9KWqxog";
        output="xml";
    }
    
    public Map geoEncode(String location) {
        
        //now lets create the request link
        String request_link = "http://maps.google.com/maps/geo?q="+location+"&output="+output+"&key="+api_key;
        InputStream reply=null;
        
        try {
            reply = HTTP.doGetRequest(request_link);
        //       System.out.println(REST.slurp(reply));
            
        } catch (Exception ex) {
            System.err.println("[geoEncode] ERROR: IOException on GET request");
            ex.printStackTrace();
        }
        
        Map map = parseMapFromXML(reply);
        
        return map;
    }
    
    private Map parseMapFromXML(InputStream xml){
        
        String coordinates = null;
        Map result = new Map();
        //Some input validation
        if(xml!=null){
            try {
                //Let's now parse the xml
                coordinates = REST.evaluate("//coordinates",xml);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            // And a quick parse of the result
            Scanner s = new Scanner(coordinates).useDelimiter(",");
            float longitude = Float.parseFloat(s.next());
            float latitude = Float.parseFloat(s.next());
            
            //Now let's just build the final resulting Map object
            result = new Map(latitude, longitude, 0);
        }
        return result;
    }
}
